import 'dart:async';

import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:flutter/material.dart';
import 'package:flutter_platform_widgets/flutter_platform_widgets.dart';

class ConfirmDialog extends StatelessWidget {
  final String title;
  final String content;
  final String confirmText;
  final String cancelText;

  const ConfirmDialog({
    super.key,
    this.title = '提示',
    required this.content,
    this.confirmText = '确认',
    this.cancelText = '取消',
  });

  @override
  Widget build(BuildContext context) {
    return PlatformAlertDialog(
      title: Text(
        title,
        style: isMaterial(context)
            ? context.textTheme.titleLarge?.copyWith(
                color: context.customColorThemeNonNull.textColor2,
              )
            : null,
      ),
      content: Padding(
        padding: const EdgeInsets.only(top: 8),
        child: Text(
          content,
          style: isMaterial(context)
              ? context.textTheme.headlineLarge?.copyWith(
                  color: context.customColorThemeNonNull.textColor2,
                )
              : null,
        ),
      ),
      actions: [
        PlatformDialogAction(
          child: Text(
            cancelText,
            style: isMaterial(context)
                ? context.textTheme.headlineLarge?.copyWith(
                    color: context.customColorThemeNonNull.textColor1,
                  )
                : null,
          ),
          onPressed: () => Navigator.of(context).pop(false),
        ),
        PlatformDialogAction(
          child: Text(
            confirmText,
            style: isMaterial(context)
                ? context.textTheme.headlineLarge?.copyWith(
                    color: context.customColorThemeNonNull.textColor1,
                  )
                : null,
          ),
          onPressed: () => Navigator.of(context).pop(true),
        ),
      ],
    );
  }
}

Future<bool> showConfirmDialog({
  required BuildContext context,
  String title = '提示',
  required String content,
  String confirmText = '确认',
  String cancelText = '取消',
}) async {
  final result = await showPlatformDialog<bool>(
    context: context,
    barrierDismissible: false,
    builder: (ctx) => ConfirmDialog(
      title: title,
      content: content,
      confirmText: confirmText,
      cancelText: cancelText,
    ),
  );

  return result ?? false;
}

Future<bool?> showCustomConfirmDialog({
  required BuildContext context,
  required String content,
  Widget? contentWidget,
  String? title,
  FutureOr<void> Function()? confirmAction,
  String confirmText = '确认',
  String cancelText = '取消',
  Color? confirmTextColor,
  Color? cancelTextColor,
  TextAlign contentAlignment = TextAlign.center,
}) async {
  final hasCancel = cancelText.trim().isNotEmpty;
  final hasConfirm = confirmText.trim().isNotEmpty;

  return await showPlatformDialog<bool>(
    context: context,
    barrierDismissible: false,
    useRootNavigator: true,

    builder: (ctx) => PlatformAlertDialog(
      title: Text(title ?? '提示'),
    
      content:
          contentWidget ??
          Text(
            content,
            textAlign: contentAlignment,
            style: context.textTheme.headlineMedium?.copyWith(
              color: confirmTextColor ?? ctx.customColorThemeNonNull.textColor3,
            ),
          ),
      actions: [
        if (hasCancel)
          PlatformDialogAction(
            child: Text(
              cancelText,
              style: context.textTheme.headlineLarge?.copyWith(
                color:
                    cancelTextColor ?? ctx.customColorThemeNonNull.textColor1,
              ),
            ),
            onPressed: () => Navigator.pop(ctx, false),
          ),
        if (hasConfirm)
          PlatformDialogAction(
            child: Text(
              confirmText,
              style: context.textTheme.headlineLarge?.copyWith(
                color: confirmTextColor ?? ctx.colorScheme.primary,
              ),
            ),
            onPressed: () async {
              if (confirmAction != null) {
                await confirmAction();
              } else {
                Navigator.pop(ctx, true);
              }
            },
          ),
      ],
    ),
  );
}

Future<String?> showInputDialog({
  required BuildContext context,
  required String title,
  String? hintText,
  String? initialValue,
  String confirmText = '确认',
  String cancelText = '取消',
  Color? confirmColor,
  Color? cancelColor,
  String? Function(String?)? customValidator, // ✅ 自定义验证函数
}) async {
  final controller = TextEditingController(text: initialValue);
  String? errorText;

  return await showPlatformDialog<String>(
    context: context,
    barrierDismissible: false,
    builder: (ctx) => StatefulBuilder(
      builder: (context, setState) {
        return PlatformAlertDialog(
          title: Text(title),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              PlatformTextField(
                controller: controller,
                material: (_, __) => MaterialTextFieldData(
                  decoration: InputDecoration(
                    hintText: hintText,
                    errorText: errorText, // ✅ 手动显示错误
                    border: OutlineInputBorder(),
                  ),
                ),
                cupertino: (_, __) =>
                    CupertinoTextFieldData(placeholder: hintText),
                onChanged: (value) {
                  if (errorText != null) {
                    setState(() => errorText = null); // 输入时清除错误
                  }
                },
              ),
              if (errorText != null) SizedBox(height: 8),
            ],
          ),
          actions: [
            PlatformDialogAction(
              material: (_, __) => MaterialDialogActionData(
                style: TextButton.styleFrom(
                  foregroundColor: cancelColor ?? Colors.grey[700],
                ),
              ),
              child: Text(cancelText),
              onPressed: () => Navigator.pop(ctx),
            ),
            PlatformDialogAction(
              material: (_, __) => MaterialDialogActionData(
                style: TextButton.styleFrom(
                  foregroundColor: confirmColor ?? Theme.of(ctx).primaryColor,
                ),
              ),
              child: Text(confirmText),
              onPressed: () {
                final value = controller.text;

                // ✅ 手动验证逻辑
                if (value.isEmpty) {
                  setState(() => errorText = '请输入内容');
                  return;
                }

                // ✅ 自定义验证（如果有）
                if (customValidator != null) {
                  final validationError = customValidator(value);
                  if (validationError != null) {
                    setState(() => errorText = validationError);
                    return;
                  }
                }

                Navigator.pop(ctx, value);
              },
            ),
          ],
        );
      },
    ),
  );
}
